package database;

import core.utils.Log;
import entity.BaseEntity;

import java.io.*;
import java.net.URL;
import java.util.Properties;

/**
 * @author 63495
 * @Description: 使用File输入输出流实现数据库读写操作//
 * @date 2022/3/25 22:36
 */
public class FileIO<T> {

    private static File file;
    private static BufferedReader reader;
    private static BufferedWriter writer;
    private static Class innerClazz;

    private FileIO(Class<? extends BaseEntity> clazz) {
        // 通过类加载器加载数据库配置文件
        URL url = FileIO.class.getClassLoader().getResource("database.properties");
        try {

            FileInputStream fileInputStream = new FileInputStream(url.getPath());
            Properties properties = new Properties();
            properties.load(fileInputStream);
            // 通过类型获取该实体类的类名作为key找到数据库txt文件路径
            String databaseName = clazz.getSimpleName().toLowerCase();
            String databaseFilePath = (String) properties.get(databaseName);
            URL resource = FileIO.class.getClassLoader().getResource(databaseFilePath);

            file = new File(resource.getPath());
            System.out.println(file.getAbsolutePath());
            reader = new BufferedReader(new FileReader(file));
            writer = new BufferedWriter(new FileWriter(file));
        } catch (IOException e) {
            Log.error("FileIO initialized fail: {}", e.getMessage());
        }
    }

    private static class FileIOInstance {
        private static FileIO fileIO = new FileIO(innerClazz);
    }

    public static FileIO getFileIOInstance(Class<? extends BaseEntity> clazz) {
        innerClazz = clazz;
        return FileIOInstance.fileIO;
    }

    public BufferedReader getReader(){
        return reader;
    }

    public BufferedWriter getWriter(){
        return writer;
    }
}
